<template>
  <el-container style="height: 100%">
    <el-main>
      <el-form
        ref="form"
        :inline-message="false"
        :rules="ruleForm"
        :status-icon="true"
        :model="formData"
        label-width="120px"
        size="large"
        :hide-required-asterisk="true"
        class="ser-form ope-form"
        :v-loading="loading"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="资源名称：" prop="resourceName" key="resourceName">
              <el-input
                placeholder="请输入资源名称"
                v-model.trim="formData.resourceName"
                v-filterSpecialChar
                :disabled="isoccupy"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <div class="warn-info ml-30">
              4-16个字符，支持汉字、字母、数字、下划线、中划线
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="数据库类型：" prop="dbDriverId" key="dbDriverId">
              <el-select @change="gettypeId" v-model="formData.dbDriverId"  :disabled="isoccupy" placeholder="--请选择--">
                <el-option
                  v-for="item in dataType"
                  :key="item.id"
                  :label="item.versionName"
                  :value="item.id.toString()"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="资源访问方式：" prop="resourceAccess"  key="resourceAccess">
              <el-radio v-model="formData.resourceAccess" :label="0" :disabled="isoccupy"
                >配置详细地址</el-radio
              >
              <el-radio v-model="formData.resourceAccess" :label="1" :disabled="isoccupy"
                >仅提供访问URL</el-radio
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.resourceAccess == 1">
          <el-col :span="8">
            <el-form-item label="URL：" prop="resourceUrl" key="resourceUrl">
              <el-input
                placeholder="请输入URL"
                v-model.trim="formData.resourceUrl"
                v-filterSpecialChar
                :disabled="isoccupy"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div class="warn-info ml-30">
               <el-popover

                    placement="top-start"
                    width="500"
                    trigger="hover"
                    v-if="curdataBase"
                  >
                  <ul v-if="curdataBase.versionName.toUpperCase().indexOf('ORACLE') > -1">
                      <li>------请参考如下格式------</li>
                      <li>ORACLE的SID方式：jdbc:oracle:thin:@Host:Port:SID</li>
                      <li>
                        ORACLE的ServerName：jdbc:oracle:thin:@//Host:Port/ServiceName
                      </li>
                      <li>
                        ORACLE集群：jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=x.x.x.1)
                      </li>
                      <li>
                        (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=xxrac)))
                      </li>
                      <li>
                        ORACLE集群：jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=x.x.x.1)
                      </li>
                      <li>
                        (PORT=1521))(ADDRESS=(PROTOCOL=TCP)(HOST=x.x.x.2)(PORT=1521)))(LOAD_BALANCE=yes)
                      </li>
                      <li>
                        (CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=xxrac)))
                      </li>
                    </ul>
                  <ul  v-if="curdataBase.versionName.toUpperCase().indexOf('SQL SERVER') > -1">
                       <li>------请参考如下格式------</li>
                      <li>
                        SQLSERVER ipv4格式：jdbc:jtds:sqlserver://Ip:Port/DbName
                      </li>
                      <li>
                        SQLSERVER ipv6格式：jdbc:jtds:sqlserver://[ip]:port/dbName
                      </li>
                  </ul>
                      <ul  v-if="curdataBase.versionName.toUpperCase().indexOf('MYSQL') > -1">
                      <li>------请参考如下格式------</li>
                      <li>
                        MYSQL IPV4:jdbc:mysql://Ip:Port/DbName
                      </li>
                      <li>
                        MYSQL IPV6:jdbc:mysql://address=(protocol=tcp)(host=ip)(port=port)/DbName
                      </li>
                  </ul>
                      <ul  v-if="curdataBase.versionName.toUpperCase().indexOf('DB2') > -1">
                      <li>------请参考如下格式------</li>
                      <li>DB2 ipv4格式：jdbc:db2://Ip:Port/DbName</li>
                      <li>DB2 ipv6格式：jdbc:db2://[ip]:port/dbName</li>
                    </ul>
                    <ul  v-if="curdataBase.versionName.toUpperCase().indexOf('SYBASE') > -1">
                        <li>------请参考如下格式------</li>
                      <li>SYBASE ipv4格式：jdbc:sybase:Tds:Ip:Port/DbName</li>
                      <li>SYBASE ipv6格式：jdbc:sybase:Tds:[ip]:port/dbName</li>
                    </ul>
                    <ul  v-if="curdataBase.versionName.toUpperCase().indexOf('达梦') > -1">
                      <li>------请参考如下格式------</li>
                      <li>DM ipv4格式：jdbc:dm://Ip:Port/DbName</li>
                      <li>DM ipv6格式：jdbc:dm://[ip]:port/dbName</li>
                    </ul>
                     <ul  v-if="curdataBase.versionName.toUpperCase().indexOf('人大金仓') > -1">
                      <li>------请参考如下格式------</li>
                      <li>
                        人大金仓 ipv4格式：jdbc:kingbase://Ip:Port/DbName
                      </li>
                      <li>
                        人大金仓 ipv6格式：jdbc:kingbase://[Ip]:Port/DbName
                      </li>
                    </ul>
                    <ul  v-if="curdataBase.versionName.toUpperCase().indexOf('南大通用') > -1">
                      <li>------请参考如下格式------</li>
                      <li>
                        南大通用： jdbc:gbase://Ip:Port/DbName
                      </li>
                    </ul>
                    <ul  v-if="curdataBase.versionName.toUpperCase().indexOf('POSTGRESQL') > -1">
                      <li>------请参考如下格式------</li>
                      <li>
                        PGSQL IPV4： jdbc:postgresql://Ip:Port/DbName
                      </li>
                      <li>
                        PGSQL IPV6： jdbc:postgresql://[Ip]:Port/DbName
                      </li>
                    </ul>
                  <i slot="reference" class="el-icon-info hov"></i>
               </el-popover>
            </div>
          </el-col>
        </el-row>
        <template v-else>
          <el-row>
            <el-col :span="8">
              <el-form-item label="IP地址：" prop="ip"  key="ip">
                <el-input
                  placeholder="请输入IP"
                  v-model.trim="formData.ip"
                  v-filterSpecialChar
                  :disabled="isoccupy"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="warn-info ml-30"></div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="端口：" prop="port"  key="port">
                <el-input
                  placeholder="请输入端口"
                  v-model.trim="formData.port"
                  v-filterSpecialChar
                  :disabled="isoccupy"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <div class="warn-info ml-30"></div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="数据库名：" prop="dbName"  key="dbName">
                <el-input
                  placeholder="请输入数据库名"
                  v-model.trim="formData.dbName"
                  v-filterSpecialChar
                  :disabled="isoccupy"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <div class="warn-info ml-30">1-128个字符，支持汉字、字母、数字、下划线、中划线</div>
            </el-col>
          </el-row>
        </template>
        <el-row>
          <el-col :span="8">
            <el-form-item label="用户名：" prop="username"  key="username">
              <el-input
                placeholder="请输入用户名"
                v-model.trim="formData.username"
                v-filterSpecialChar
                :disabled="isoccupy"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <div class="warn-info ml-30">
              1-100个字符，特殊字符支持`~!@#$%^&*()-_=+\|[{}];:'",<.>/?
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="密码：" prop="password" key="password">
              <el-input
                placeholder="请确认密码"
                v-model.trim="formData.password"
                v-filterSpecialChar
                type="password"
                onpaste="return false"
                onselectstart="return false"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <div class="warn-info ml-30">
               1-100个字符，特殊字符支持`~!@#$%^&*()-_=+\|[{}];:'",<.>/?
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="编码：" prop="unicodeId" key="unicodeId">
              <el-select v-model="formData.unicodeId" >
                <el-option
                  v-for="item in $code.getByType('unicode')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row  v-show="false">
          <el-col>
            <el-form-item label="连接方式：" prop="connectionMode"  key="connectionMode">
              <el-radio v-model="formData.connectionMode" :label="0"
                >长连接</el-radio
              >
              <el-radio v-model="formData.connectionMode" :label="1"
                >短连接</el-radio
              >
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系人：" prop="manager" key="manager">
              <el-input
                placeholder="请输入联系人"
                v-model.trim="formData.manager"
                v-filterSpecialChar
              ></el-input>
            </el-form-item>
          </el-col>
        <el-col :span="16">
            <div class=" mark ml-30">
                  2-20个字符，支持汉字
              </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系方式：" prop="phone" key="phone">
              <el-input
                placeholder="请输入联系方式"
                v-model.trim="formData.phone"
                v-filterSpecialChar
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item
              label="备注："
              label-width="120px"
              class="remarkBox"
              prop="remark"
              key="remark"
            >
              <el-input
                v-model="formData.remark"
                type="textarea"
                placeholder="请输入备注"
                maxlength="200"
                show-word-limit
                v-filterSpecialChar
              />
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <div class=" mark ml-30">
              1-200个字符，支持汉字、字母、数字、下划线
            </div>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item>
              <el-button size="medium" @click="onBack()">取消</el-button>
              <el-button
                size="medium"
                type="primary"
                @click="onSave()"
                :loading="saveLoading"
                >保存</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>

        <div style="margin-top: 60px"></div>
      </el-form>
    </el-main>
  </el-container>
</template>
<script>
import {
  validResourceName,
  IP,
  Port,
  validDatabase,
  isPhone,
  isURL,
  validUser,
  validUserpass,
  validdataContact,
  validRemark,
  validresgeneral,
  validresgeneralmid,
  validresMask,
  validContact
} from '@/util/customRules'
import encrypt from '@/util/encrypt'
export default {
  name: 'DATABaseConfig',
  data() {
    return {
      dataType: [],
      ruleForm: {
        resourceName: [
          { required: true, message: '请输入资源地址', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              let me = this
              validresgeneralmid(rule, value, 4, 16, function(error) {
                if (error) {
                  callback(error)
                } else {
                  me.$api.resourcemanage
                    .isResourceName({
                      resourceName: value,
                      resourceId: me.params.type == 'modify'? me.params.id:'',
                      resourceTypeId: '02',
                    })
                    .then((res) => {
                      if (
                        res.data.code == 200 &&
                        res.data.msg == '资源名称可用'
                      ) {
                        callback()
                      } else {
                        callback(new Error('资源名称已经存在!'))
                      }
                    })
                    .catch((err) => {
                      console.log(err)
                      callback(new Error('资源名称已经存在!'))
                    })
                }
              })
            },
            trigger: 'blur',
          },
        ],
        dbDriverId: [
          { required: true, message: '请选择数据库类型', trigger: 'change' },
        ],
        ip: [
          { required: true, message: '请输入IP地址', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              IP(rule, value, callback)
            },
            trigger: 'blur',
          },
        ],
        port: [
          { required: true, message: '请输入端口号', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              Port(rule, value, callback)
            },
            trigger: 'blur',
          },
        ],
        resourceUrl: [
          {
            required: true,
            message: '请输入URL',
            trigger: 'blur',
          },
          // {
          //   validator: (rule, value, callback) => {
          //     isURL(rule, value, callback)
          //   },
          //   trigger: 'blur',
          // },
        ],
        dbName: [
          { required: true, message: '请输入数据库名', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              validresgeneralmid(rule, value, 1, 128, callback);
            },
            trigger: 'blur'
          }
        ],
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              validUser(rule, value, callback)
            },
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              validUserpass(rule, value, callback)
            },
            trigger: 'blur',
          },
        ],
        manager: [
          {
            validator: (rule, value, callback) => {
              validdataContact(rule, value, callback)
            },
            trigger: 'blur',
          },
        ],
        phone: [
          {
            validator: (rule, value, callback) => {
              isPhone(rule, value, callback)
            },
            trigger: 'blur',
          },
        ], remark: [{
          validator: validresMask,
          trigger: 'blur'
        }],
      },
      formData: {
        typeId: '',
        resourceName: '', // 资源名
        dbDriverId: '', // 数据库类型id（数据库类型的value值）
        resourceAccess: 0, // 资源访问方式 0: 详细地址 1:url地址连接
        resourceUrl: '',
        ip: '',
        port: '',
        dbName: '',
        username: '',
        password: '',
        unicodeId: '01', // 编码格式 01 UTF-8、02 GBK
        connectionMode: 0, // 连接方式 0: 长连接 1:短连接
        // 联系人
        manager: '',
        // 联系方式
        phone: '',
        // typeId: '',
        remark: '',
      },
      saveLoading: false,
      loading: false,
      database: [],
      curdataBase: '',
    }
  },
  props: {
    params: {
      type: Object,
      default: {},
    },
  },
  computed: {
    isoccupy() {
      if (this.formData.dbTaskVoList && this.formData.dbTaskVoList.length>0) {
        return true
      } else {
        return false
      }
    }
  },
  // watch:{
  //   'formData.dbDriverId':{
  //      handler(val, oldVal){
  //        if(this.database.length>0){
  //          this.formData.typeId = this.database.find(e =>e.id == val).resourceTypeId
  //        }
  //      },
  //      immediate: true
  //   }
  // },
  async created() {
    await this.getDatabase()
    if (this.params.type == 'modify') {
      this.loadData()
    }
  },
  mounted() {
  },
  methods: {
    // 根据id查询
    loadData() {
      this.loading = true
      this.$api.resourcemanage
        .getDbById(this.params.id)
        .then((res) => {
          const result = res.data
          if (result.code === 200) {
            let data = result.data;
            this.formData = data;
            this.curdataBase = this.dataType.find(e => e.id == this.formData.dbDriverId);
            for (let key in data) {
              if (this.formData.hasOwnProperty(key)) {
                if (key == 'password') {
                  this.formData[key] = encrypt.decrypt(data[key]);
                } else {
                  this.formData[key] = data[key]
                }
              }
            }
          }
          this.loading = false
        })
        .catch((e) => {
          this.loading = false
        })
    },
    // 获取数据库类型
    getDatabase() {
      this.$api.resourcemanage.getDatabase().then((res) => {
        if (res.data.code == 200) {
          this.dataType = res.data.data
        }
      })
    },
    // 取消
    onBack() {
      this.$confirm(
        (this.params.type == 'add' ? '新建' : '修改') +
          '操作尚未保存，是否确认退出？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(() => {
        this.$emit('changeComponent', {
          active: 'databaseresource',
        })
      })
    },
    // 测试连接
    async testConnection() {
      this.saveLoading = true;
      return this.$api.resourcemanage.datatestConnection
        .call(this, this.getTestformdata())
        .then((result) => {
          this.saveLoading = false;
          if (result.data.code === 200) {
            this.$message({
              message: result.data.msg,
              type: 'success',
            })
            return true
          } else {
            this.$message({
              message: result.data.msg,
              type: 'error',
            })
            return false
          }
        })
        .catch(() => {
          this.saveLoading = false;
          return false
        })
    },
    // 保存
    onSave() {

      this.$refs.form.validate(async(valid) => {
        if (valid) {
          this.$confirm('保存之前必须测试连接，连接成功方可保存！是否继续？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }).then(async() => {
            let result = await this.testConnection()
            if (result) {
              if (this.params.type == 'modify') {
                this.editData()
              } else {
                this.addData()
              }
            }
          })
        }
      })
    },
    addData() {
      this.saveLoading = true;
      this.$api.resourcemanage.databaseAdd
        .call(this, this.getformData())
        .then((res) => {
          this.saveLoading = false;
          if (res.data.code == 200) {
            this.$message({
              message: res.data.msg,
              type: 'success',
              onClose: () => {
                this.link()
              },
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error',
            })
          }
        })
        .catch(() => {
          this.saveLoading = false;
        })
    },
    editData() {
      this.saveLoading = true;
      this.$api.resourcemanage.databasemodify
        .call(this, { ...this.getformData(), resourceId: this.params.id })
        .then((res) => {
          this.saveLoading = false;
          if (res.data.code == 200) {
            this.$message({
              message: res.data.msg,
              type: 'success',
              onClose: () => {
                this.link()
              },
            })
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error',
            })
          }
        })
        .catch(() => {
          this.saveLoading = false;
        })
    },
    link() {
      this.$emit('changeComponent', {
        active: 'databaseresource',
      })
    },
    getformData() {
      let result;
      if (this.formData.resourceAccess == 1) {
        let { ip, port, dbName, ...params } = this.formData;
        result = params;
      } else {
        let { resourceUrl, ...params } = this.formData;
        result = params;
      }
      result.password = encrypt.encrypt(this.formData.password);
      return result
    },
    getTestformdata() {
      let result;
      if (this.formData.resourceAccess == 1) {
        let { ip, port, dbName, remark, phone, manager, ...params } = this.formData;
        result = params;
      } else {
        let { resourceUrl, remark, phone, manager, ...params } = this.formData;
        result = params;
      }
      result.password = encrypt.encrypt(this.formData.password);
      return result
    },
    gettypeId(val) {
      this.curdataBase = this.dataType.find(e => e.id == val);
      this.formData.typeId = this.curdataBase.resourceTypeId;
    }
  },
}
</script>
<style lang="less" scoped>
.textareaInput {
  // height: 80px;
  padding: 5px;
}
</style>
